<template>
  <el-card>
    <template #header><h2>客户管理</h2></template>

    <el-form :inline="true" :model="filters" class="toolbar">
      <el-form-item label="客户名">
        <el-input v-model="filters.name" placeholder="模糊搜索" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchCustomers">查询</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="customers" stripe>
      <el-table-column prop="name" label="客户名" />
      <el-table-column prop="type" label="类型" />
      <el-table-column prop="gender" label="性别" />
      <el-table-column prop="age" label="年龄" />

      <el-table-column label="护理级别">
        <template #default="{ row }">
          <el-tag v-if="row.careLevelId" type="info">{{ row.levelName }}</el-tag>
          <span v-else>未设置</span>
        </template>
      </el-table-column>

      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button
            v-if="!row.careLevelId"
            size="small"
            type="primary"
            @click="setLevel(row)"
          >设置级别</el-button>
          <el-button
            v-else
            size="small"
            type="warning"
            @click="removeLevel(row)"
          >移除级别</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="page.current"
      :page-size="page.size"
      :total="page.total"
      @current-change="fetchCustomers"
    />
  </el-card>
</template>

<script setup>
import { ref, reactive, onMounted, inject } from 'vue'
import qs from 'qs'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'

const axios = inject('axios')
const router = useRouter()

// 搜索条件、列表、分页
const filters = reactive({ name: '' })
const customers = ref([])
const page = reactive({ current: 1, size: 10, total: 0 })

// 护理级别映射：id → levelName
const levelMap = reactive({})

// 1. 预加载所有护理级别
async function loadCareLevels() {
  const resp = await axios.get('/CareLevelController/queryByStatus', {
    params: { status: null, cur: 1, number: 999 }
  })
  resp.data.data.forEach(lv => {
    levelMap[lv.id] = lv.levelName
  })
}

// 2. 拉客户列表并且填充 careLevelId、levelName
async function fetchCustomers() {
  // 2.1 查询客户
  const resp = await axios.post(
    '/CustomerController/queryAll',
    qs.stringify({
      name: filters.name,
      cur: page.current,
      number: page.size
    })
  )
  customers.value = resp.data.data
  page.total = resp.data.total

  // 2.2 逐条拉护理级别配置
  await Promise.all(
    customers.value.map(async row => {
      try {
        const r2 = await axios.get(
          '/CustomerCareLevelController/getCustomerCareLevel',
          { params: { customerId: row.id } }
        )
        const ccl = r2.data.data
        if (ccl && ccl.careLevelId) {
          row.careLevelId = ccl.careLevelId
          row.levelName = levelMap[ccl.careLevelId] || ''
        } else {
          row.careLevelId = null
          row.levelName = ''
        }
      } catch {
        row.careLevelId = null
        row.levelName = ''
      }
    })
  )
}

function setLevel(row) {
  router.push({
    path: '/ConfigDetail',
    query: { customerId: row.id }
  })
}

async function removeLevel(row) {
  await ElMessageBox.confirm(
    `移除客户【${row.name}】护理级别，将同时清除其所有购买项目？确认操作吗？`,
    '警告',
    { type: 'warning' }
  )
  await axios.post(
    '/CustomerCareLevelController/removeCareLevel',
    qs.stringify({ customerId: row.id })
  )
  ElMessage.success('已移除护理级别及所有项目')
  fetchCustomers()
}

onMounted(async () => {
  await loadCareLevels()
  await fetchCustomers()
})
</script>

<style scoped>
.toolbar { margin-bottom: 16px; }
</style>
